import React, { useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'
// 引入react截图
import Cropper from 'react-cropper'
// 引入对话框
import { Modal } from 'antd';
// 引入仓库方法
import { updateImage } from '@/store/modules/modules'
function Cropping({ isModalOpen, setIsModalOpen }: any) {
    const currentcomponent = useSelector((state: any) => state.reducer.currentcomponent)
    // 给裁剪绑定ref
    const cropperRef = useRef<any>(null)
    const dispatch = useDispatch()
    const handleCancel = () => {
        setIsModalOpen(false);
    }
    const handleOk = () => {
        //实现裁剪
        if (cropperRef.current) {
            //创建实例
            const cropper = cropperRef.current.cropper;
            // 调用了Cropper实例的getCroppedCanvas方法，它返回一个裁剪后的图像的canvas对象。这个canvas对象包含了被裁剪后的图像数据
            const canvasData = cropper.getCroppedCanvas();
            // canvas对象转换为Base64编码的图像数据URL。toDataURL方法的参数指定了输出的图像格式
            const image = canvasData.toDataURL('image/png');
            //更新仓库
            dispatch(updateImage({ image: image, width: canvasData.width, height: canvasData.height }))
        }
        setIsModalOpen(false);
    }
    return (
        <Modal title="裁剪" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Cropper ref={cropperRef} src={currentcomponent ? currentcomponent.propLable : ''} style={{ height: 400, width: '100%' }} />
        </Modal>
    )
}

export default Cropping
